package com.example.bdd.demo.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

@Slf4j
public class FileUtil {

    public static ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
        // 美化输出
        //mapper.enable(SerializationFeature.INDENT_OUTPUT);
        // 设置时间格式
        //mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        // 设置输出时包含属性的风格
        //mapper.setSerializationInclusion(Include.NON_EMPTY);
        //mapper.setSerializationInclusion(Include.NON_DEFAULT);
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    }

    public static <T> T convert(String json, Class<T> classz) {
        if (json == null) {
            return null;
        }
        try {
            return mapper.readValue(json, classz);
        } catch (IOException e) {
            log.error("转换对象异常", e);
        }
        return null;
    }

    public static Set<String> readFileByLines(String fileName) {
        Set<String> contents = new TreeSet<>();
        try {
            File file = new File(fileName);
            Scanner scanner = new Scanner(file);
            int i = 0;
            while (scanner.hasNextLine()){
                String line = scanner.nextLine();
                if (StringUtils.isNotBlank(line)) {
                    String[] strings = line.split("=");
                    contents.add(line);
                }
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
        }
        return contents;
    }

    public static String readFile(String fileName) {
        StringBuffer contents = new StringBuffer();
        try {
            File file = new File(fileName);
            Scanner scanner = new Scanner(file);
            int i = 0;
            while (scanner.hasNextLine()){
                String line = scanner.nextLine();
                //System.out.println("line " + (++i) + ":" + line);
                if (StringUtils.isNotBlank(line)) {
                    contents.append(line);
                }
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
        }
        return contents.toString();
    }

}
